#!/bin/bash

# Agent Workspace Startup Script
# Usage: ./start-agent-workspace.sh [--stop]

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PID_FILE="$SCRIPT_DIR/.agent-workspace.pid"
BACKEND_PORT=8080
FRONTEND_PORT=3001
API_TOKEN="testtoken"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log() {
    echo -e "${GREEN}[$(date +'%H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[$(date +'%H:%M:%S')] WARNING:${NC} $1"
}

error() {
    echo -e "${RED}[$(date +'%H:%M:%S')] ERROR:${NC} $1"
}

# Function to check if a port is in use
is_port_in_use() {
    local port=$1
    if command -v lsof >/dev/null 2>&1; then
        lsof -i:$port >/dev/null 2>&1
    elif command -v netstat >/dev/null 2>&1; then
        netstat -tuln | grep -q ":$port "
    else
        # Fallback: try to connect
        (echo >/dev/tcp/localhost/$port) >/dev/null 2>&1
    fi
}

# Function to find PIDs using specific ports
find_pid_by_port() {
    local port=$1
    if command -v lsof >/dev/null 2>&1; then
        lsof -ti:$port
    elif command -v netstat >/dev/null 2>&1; then
        netstat -tulpn 2>/dev/null | grep ":$port " | awk '{print $7}' | cut -d'/' -f1
    fi
}

# Function to stop services
stop_services() {
    log "Stopping Agent Workspace services..."

    # Kill processes using our ports
    for port in $BACKEND_PORT $FRONTEND_PORT; do
        local pids=$(find_pid_by_port $port)
        if [[ -n "$pids" ]]; then
            log "Stopping processes on port $port: $pids"
            echo "$pids" | xargs -r kill -TERM 2>/dev/null || true
            sleep 2
            # Force kill if still running
            echo "$pids" | xargs -r kill -KILL 2>/dev/null || true
        fi
    done

    # Kill any remaining aw-web or npm processes
    pkill -f "aw-web" 2>/dev/null || true
    pkill -f "next dev" 2>/dev/null || true

    # Remove PID file
    rm -f "$PID_FILE"

    log "Services stopped"
}

# Function to check if services are healthy
check_health() {
    local backend_ok=false
    local frontend_ok=false

    # Check backend
    if curl -s -H "X-AW-Token: $API_TOKEN" "http://localhost:$BACKEND_PORT/healthz" >/dev/null 2>&1; then
        backend_ok=true
    fi

    # Check frontend (Next.js serves a page at root)
    if curl -s "http://localhost:$FRONTEND_PORT" >/dev/null 2>&1; then
        frontend_ok=true
    fi

    echo "$backend_ok,$frontend_ok"
}

# Function to start services
start_services() {
    log "Starting Agent Workspace..."

    # Check if already running
    if [[ -f "$PID_FILE" ]]; then
        warn "PID file exists. Checking if services are running..."
        local health=$(check_health)
        if [[ "$health" == "true,true" ]]; then
            log "Services are already running!"
            log "Backend: http://localhost:$BACKEND_PORT"
            log "Frontend: http://localhost:$FRONTEND_PORT"
            return 0
        else
            warn "PID file exists but services not healthy. Cleaning up..."
            stop_services
        fi
    fi

    # Check if ports are available
    if is_port_in_use $BACKEND_PORT; then
        error "Port $BACKEND_PORT is already in use"
        return 1
    fi

    if is_port_in_use $FRONTEND_PORT; then
        error "Port $FRONTEND_PORT is already in use"
        return 1
    fi

    # Check if virtual environment exists
    if [[ ! -d "$SCRIPT_DIR/.venv" ]]; then
        error "Virtual environment not found. Please run: python3 -m venv .venv && .venv/bin/activate && pip install -e ."
        return 1
    fi

    # Check if webapp directory exists
    if [[ ! -d "$SCRIPT_DIR/webapp" ]]; then
        error "Webapp directory not found"
        return 1
    fi

    # Start backend
    log "Starting FastAPI backend on port $BACKEND_PORT..."
    cd "$SCRIPT_DIR"
    (
        source .venv/bin/activate
        export AW_API_TOKEN="$API_TOKEN"
        aw-web --host 0.0.0.0 --port $BACKEND_PORT
    ) >>"$SCRIPT_DIR/backend.log" 2>&1 &

    local backend_pid=$!
    echo "$backend_pid" > "$PID_FILE"

    # Wait for backend to start
    log "Waiting for backend to start..."
    local attempts=0
    while [[ $attempts -lt 30 ]]; do
        if curl -s -H "X-AW-Token: $API_TOKEN" "http://localhost:$BACKEND_PORT/healthz" >/dev/null 2>&1; then
            log "Backend started successfully"
            break
        fi
        sleep 1
        ((attempts++))
    done

    if [[ $attempts -eq 30 ]]; then
        error "Backend failed to start"
        stop_services
        return 1
    fi

    # Start frontend
    log "Starting Next.js frontend on port $FRONTEND_PORT..."
    cd "$SCRIPT_DIR/webapp"
    npm run dev >>"$SCRIPT_DIR/frontend.log" 2>&1 &

    local frontend_pid=$!
    echo "$frontend_pid" >> "$PID_FILE"

    # Wait for frontend to start
    log "Waiting for frontend to start..."
    attempts=0
    while [[ $attempts -lt 60 ]]; do
        if curl -s "http://localhost:$FRONTEND_PORT" >/dev/null 2>&1; then
            log "Frontend started successfully"
            break
        fi
        sleep 1
        ((attempts++))
    done

    if [[ $attempts -eq 60 ]]; then
        error "Frontend failed to start"
        stop_services
        return 1
    fi

    # Show status
    echo ""
    log "🎉 Agent Workspace is running!"
    echo -e "  ${BLUE}Backend API:${NC} http://localhost:$BACKEND_PORT"
    echo -e "  ${BLUE}Frontend App:${NC} http://localhost:$FRONTEND_PORT"
    echo -e "  ${BLUE}API Token:${NC} $API_TOKEN"
    echo ""
    log "Test the API:"
    echo "  curl -H \"X-AW-Token: $API_TOKEN\" \"http://localhost:$BACKEND_PORT/api/v1/accounts\""
    echo ""
    log "Logs:"
    echo "  Backend: $SCRIPT_DIR/backend.log"
    echo "  Frontend: $SCRIPT_DIR/frontend.log"
    echo ""
    log "To stop: $0 --stop"
}

# Main logic
case "${1:-}" in
    --stop|-s)
        stop_services
        ;;
    --help|-h)
        echo "Agent Workspace Startup Script"
        echo ""
        echo "Usage: $0 [OPTIONS]"
        echo ""
        echo "Options:"
        echo "  (none)    Start both backend and frontend services"
        echo "  --stop    Stop all services"
        echo "  --help    Show this help message"
        echo ""
        echo "Services:"
        echo "  Backend:  FastAPI server on port $BACKEND_PORT"
        echo "  Frontend: Next.js app on port $FRONTEND_PORT"
        ;;
    "")
        start_services
        ;;
    *)
        error "Unknown option: $1"
        echo "Use --help for usage information"
        exit 1
        ;;
esac